package com.zkzx.company.base.service;

import com.zkzx.common.company.model.CompanyFinanceVO;
import com.zkzx.company.base.mapper.CompanyFinanceMapper;
import com.zkzx.company.base.mapper.entity.CompanyFinance;
import com.zkzx.company.base.mapper.entity.CompanyFinanceExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @author young Email:yanghui@zkraising.com
 * @description
 * @company 北京中科智兴物联科技有限公司 @版权所有
 * @since 2021年04月30日 10时19分
 */
@Service
public class CompanyFinanceService {

    @Resource
    private CompanyFinanceMapper companyFinanceMapper;

    /**
     * 根据企业id查询金融信息
     * @param companyId 企业id
     * @return 金融信息
     */
    public CompanyFinanceVO findVOByCompanyId(Integer companyId){
        CompanyFinance companyFinance = findByCompanyId(companyId);
        if(Objects.isNull(companyFinance)){
            return null;
        }
        return CompanyFinanceVO.builder()
                .bank(companyFinance.getBank())
                .bankAmount(companyFinance.getBankamount())
                .amount(companyFinance.getAmount())
                .build();
    }

    /**
     * 根据企业id查询金融信息
     * @param companyId 企业id
     * @return 金融信息
     */
    public CompanyFinance findByCompanyId(Integer companyId){
        CompanyFinanceExample financeExample = new CompanyFinanceExample();
        financeExample.createCriteria().andCompanyidEqualTo(companyId);
        Optional<CompanyFinance> companyFinanceOne = companyFinanceMapper.selectByExample(financeExample).stream().findFirst();

        CompanyFinance companyFinance  = null;
        if(companyFinanceOne.isPresent()){
            companyFinance = companyFinanceOne.get();
        }
        return companyFinance;
    }

    /**
     * 更新金融信息
     * @param companyFinance 金融信息
     */
    public void updateOrInsert(CompanyFinance companyFinance){
        if (Objects.isNull(companyFinance)){
            return;
        }
        // 主键为空是新增
        if (Objects.isNull(companyFinance.getId()) && Objects.nonNull(companyFinance.getCompanyid())){
            companyFinanceMapper.insert(companyFinance);
        }else {
            // 主键不为空则修改
            companyFinanceMapper.updateByPrimaryKey(companyFinance);
        }
    }
}
